/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年10月19日
 */
package com.massyframework.beanskin.scriptengine.beancontext;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import javax.script.ScriptContext;
import javax.script.ScriptEngine;

import com.massyframework.beanskin.assembly.beans.BeanContextAdapter;
import com.massyframework.beanskin.assembly.beans.BeanNotFoundException;

/**
 * 基于Bindings的BeanContextAdapter.
 * @author huangkh
 *
 */
public class ScriptEngineContextAdapter  implements BeanContextAdapter {

	private static final Set<String> CLASSNAMES = new HashSet<>(Arrays.asList(
			"jdk.internal.dynalink.beans.StaticClass",
			"com.oracle.truffle.polyglot.PolyglotMapAndFunction"
			));
	private static final Set<String> METHODNAMES = new HashSet<>(Arrays.asList(
			"com.oracle.truffle.polyglot.PolyglotMap"));
	
	private final ScriptEngine engine;
	
	/**
	 * 
	 */
	public ScriptEngineContextAdapter(ScriptEngine engine) {
		this.engine = Objects.requireNonNull(engine, "\"engine\" cannot be null.");
	}

	@Override
	public boolean containsBean(String beanName) {
		Object result =  this.findBean(beanName);
		return result != null;
	}

	@Override
	public Object getBean(String beanName) throws BeanNotFoundException {
		Object result =  this.findBean(beanName);
		if (result == null) {
			throw new BeanNotFoundException(beanName);
		}		
		return result;
	}

	@Override
	public Class<?> getBeanType(String beanName) throws BeanNotFoundException {
		Object result = this.getBean(beanName);
		return result.getClass();
	}

	@Override
	public <B> Map<String, B> getBeansOfType(Class<B> beanType) {
		Map<String, B> result = new HashMap<>();
		
		Map<String, Object> objectMap = this.engine.getBindings(ScriptContext.ENGINE_SCOPE);
		for (Map.Entry<String, Object> entry: objectMap.entrySet()) {
			Object value = entry.getValue();
			if (value != null) {
				Class<?> clazz = entry.getValue().getClass();
				if (beanType.isAssignableFrom(clazz)) {
					result.put(entry.getKey(), beanType.cast(entry.getValue()));
				}
			}
		}
		return result;
	}

	@Override
	public Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annoType) {
		Map<String, Object> result = new HashMap<>();
		
		Map<String, Object> objectMap = this.engine.getBindings(ScriptContext.ENGINE_SCOPE);
		for (Map.Entry<String, Object> entry: objectMap.entrySet()) {
			Class<?> clazz = entry.getValue().getClass();
			if (clazz.isAnnotationPresent(annoType)) {
				result.put(entry.getKey(), entry.getValue());
			}
		}
		return result;
	}

	@Override
	public List<String> getBeanNames() {
		List<String> result = new ArrayList<>();
		
		Map<String, Object> objectMap = this.engine.getBindings(ScriptContext.ENGINE_SCOPE);
		for (Map.Entry<String, Object> entry: objectMap.entrySet()) {
			Class<?> clazz = entry.getValue().getClass();
			if (!this.isStaticClass(clazz)) {
				result.add(entry.getKey());
			}
		}
		return result;
	}
	
	public ScriptEngine getScriptEngine() {
		return this.engine;
	}
	
	/**
	 * 按{@code beanName}查找Bean实例
	 * @param beanName {@link String}, bean名称
	 * @return {@link Object}
	 */
	protected Object findBean(String beanName) {
		Object result = this.engine.getBindings(ScriptContext.ENGINE_SCOPE).get(beanName);
		if (result != null && !this.isStaticClass(result.getClass())) {
			return result;
		}
		return null;
	}

	/**
	 * 判断{@code clazz}是否为静态类型
	 * @param clazz {@link Class}
	 * @return {@link boolean},返回{@code true}表示是，否则返回{@code false}
	 */
	public boolean isStaticClass(Class<?> clazz) {
		return CLASSNAMES.contains(clazz.getName());
	}
	
	/**
	 * 判断{@code clazz}是否为脚本中的函数
	 * @param clazz {@link Class}
	 * @return {@link boolean},返回{@code true}表示是，否则返回{@code false}
	 */
	public boolean isFunction(Class<?> clazz) {
		return METHODNAMES.contains(clazz.getName());
	}
	
	
}
